package com.guosifan.controller;

import com.guosifan.entity.Admin;
import com.guosifan.entity.Msg;
import com.guosifan.entity.User;
import com.guosifan.feign.AccountClientFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/client/account")
public class AccountClientController {

    @Autowired
    private AccountClientFeign accountClientFeign;

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        @RequestParam("type") String type, HttpSession session) {
        Object login = null;
        //返回的值为：LinkedHashMap
        login = accountClientFeign.login(username, password, type);
        LinkedHashMap<String, Object> map = (LinkedHashMap) login;

        System.out.println("login :" + login);

        if (login != null) {

            if ("user".equals(type)) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                User user = new User();
                user.setId((Integer) map.get("id"))
                    .setUsername((String) map.get("username"))
                    .setPassword((String) map.get("password"))
                    .setNickname((String) map.get("nickname"));
                session.setAttribute("user", user);
                return "redirect:/index.html";
            }
            if("admin".equals(type)){
                Admin admin = new Admin();
                admin.setId((Integer) map.get("id")).setUsername((String)map.get("username")).setPassword((String)map.get("password"));
                session.setAttribute("admin", admin);
                return "redirect:/main.html";
            }


        }
        return "redirect:/login.html";
    }


    /**
     * /client/account/getUsername
     */
    @GetMapping("/getUsername")
    @ResponseBody
    public  Msg getUsername(HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        Admin admin = (Admin)httpSession.getAttribute("admin");
        return Msg.success().add("user",user).add("admin", admin);
    }

    /**
     * /client/account/logout/admin
     */
    @GetMapping("/logout/{type}")
    public String logout(@PathVariable("type")String type,HttpSession session){
        switch (type){
            case "user":
                session.removeAttribute("user");
                break;
            case "admin":
                session.removeAttribute("admin");
                break;
        }
        System.out.println("/client/account/logout/admin");
        return "redirect:/login.html";
    }




}
